﻿using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class CustomAdminPagesPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly ICustomAdminPagesView _view;

        public IDiskAccess DiskAccess { get; set; }

        public CustomAdminPagesPresenter(ICustomAdminPagesView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }

        public CustomAdminPagesPresenter(ICustomAdminPagesView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.CustomAdminPages)
                _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            SetCustomAdminPages();
        }

        public void SetCustomAdminPages()
        {
            _view.SetCustomAdminPages(SystemRepository.GetCustomAdminPages(_administrator.CurrentSite.ID));
        }

        public void DeleteCustomAdminPage(int id)
        {
            CustomAdminPage customAdminPage = SystemRepository.GetCustomAdminPage(id);
            DiskAccess.DeleteFile("__System\\CustomAdminPages\\" + customAdminPage.Filename);
            DiskAccess.DeleteFile("__System\\CustomAdminPages\\" + customAdminPage.Filename.TrimEnd(".aspx".ToCharArray()) + ".xml");
            SystemRepository.DeleteCustomAdminPage(id);
            SetCustomAdminPages();
        }

    }
}